import React, { useState, useEffect } from 'react';
import { Table, Button, Alert, message, Row, Col, Card } from 'antd';
import { connect, FormattedMessage, request, useIntl } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { DownloadOutlined } from '@ant-design/icons';

const apiURL = '/api/services/app/ERPReports/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(true);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [dataSource2, setDataSource2] = useState([]);
  const [dyColumns, setDyColumns] = useState([]);
  const [record, setRecord] = useState<any>(null);
  const [loading2, setLoading2] = useState(false);
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, pageSize]);

  const fetchDatas = async () => {
    setLoading(true);
    let items: any = [];
    await request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        skipCount: (pageIndex - 1) * pageSize,
        maxResultCount: pageSize,
        reportType: 'UserRpt',
        isAuth: true,
        modularName: props.route.name === 'UserReport' ? null : props.route.name,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          items = response.result?.items;
          setDataSource(items);
        }
      }
      setLoading(false);
    });
    return items;
  };

  const setCurrent = (record?: any) => {
    request(apiURL + 'GetReportObj', {
      method: 'GET',
      params: { id: record.id },
    }).then((response) => {
      if (response) {
        if (response.success) {
          try {
            const result = response.result;
            setVisible(false);
            setDataSource2([]);
            setDyColumns(result.filedList);
            setRecord(result);
          } catch {}
        }
      }
    });
  };

  const runSQL = async (params: any = null) => {
    if (!record) {
      return [];
    }
    const result: any = {
      data: [],
      total: 0,
    };
    setDataSource2([]);
    Object.keys(params).map((key) => {
      if (params[key] === 'true') {
        params[key] = true;
      } else if (params[key] === 'false') {
        params[key] = false;
      }
    });
    await request(apiURL + 'RunSQL', {
      method: 'POST',
      data: { id: record.id, args: params },
    }).then((response) => {
      if (response) {
        if (response.success) {
          result.data = response.result;
          result.total = response.totalCount;
          setDataSource2(response.result);
        }
      }
    });
    return result;
  };

  const onSelectChange = (record: any) => {
    setCurrent(record);
  };

  const handlerExport = async (data: any, record: any) => {
    if (!data || data.length <= 0) {
      message.warning(intl.formatMessage({id:'pages.exportNoData'}));
      return;
    }
    setLoading2(true);
    const resp = await request('/api/Excel/ExportReport', {
      method: 'POST',
      responseType: 'blob',
      data: {
        args: data,
        reportId: record.id,
      },
    });
    const url = window.URL.createObjectURL(resp);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ExportReport.xls';
    a.click();
    setLoading2(false);
  };

  const columns = [
    {
      title: <FormattedMessage id="ReportName" />,
      dataIndex: 'reportName',
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Row gutter={16}>
        <Col span={4}>
          <Card>
            <Table
              showHeader={false}
              loading={loading}
              rowKey="id"
              key="id"
              columns={columns}
              dataSource={dataSource}
              pagination={false}
              rowSelection={{
                type: 'radio',
                onSelect: onSelectChange,
              }}
              bordered
              onRow={(rec) => {
                return {
                  onDoubleClick: () => {
                    setCurrent(rec);
                  },
                };
              }}
            />
          </Card>
        </Col>
        <Col span={20}>
          <ProTable
            headerTitle={record?.reportName}
            columns={dyColumns}
            rowKey={record?.rowKey}
            key={record?.rowKey}
            bordered={record?.bordered}
            search={{
              filterType: record?.filterType,
            }}
            scroll={{ x: 'max-content', y: record?.reportHeight ? record?.reportHeight : 300 }}
            request={async (params = {}) => {
              return runSQL(params);
            }}
            toolBarRender={() => [
              <Button
                type="primary"
                key="out"
                loading={loading2}
                onClick={() => handlerExport(dataSource2, record)}
                hidden={record?.hiddenExport}
              >
                <span>
                  <FormattedMessage id="pages.export" />
                </span>
                <DownloadOutlined />
              </Button>,
            ]}
          />
        </Col>
      </Row>
    </PageHeaderWrapper>
  );
};

export default ViewPage;
